package com.apache.bid.controller.admin;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.common.vo.BidItemCacheVo;
import com.apache.bid.controller.BaseSupperAction;
import com.apache.bid.entity.BidItem;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.entity.BidPub;
import com.apache.bid.entity.BidSession;
import com.apache.bid.manager.BidItemManager;
import com.apache.bid.manager.BidItemPriceManager;
import com.apache.bid.manager.BidPubManager;
import com.apache.bid.manager.BidSessionManager;
import com.apache.bid.manager.UnityBaseManager;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;

@Controller
@RequestMapping("/admin/item")
public class BidItemAction extends BaseSupperAction<BidItem> {

	@Autowired
	private BidItemManager bidItemManager;
	@Autowired
	private BidItemPriceManager bidItemPriceManager;
	@Autowired
	private ProxyManager wbdProxyManager;
	@Autowired
	private BidPubManager bidPubManager;
	@Autowired
	private BidSessionManager bidSessionManager;

	@Override
	protected Object listData(HttpServletRequest request, BidItem item, String page, String rows) {
		ParamsVo<BidItem> vo = new ParamsVo<BidItem>();
		if (StrUtil.isNotNull(item.getItemName())) {
			try {
				if (item.getItemName().equals(new String(item.getItemName().getBytes("iso8859-1"), "iso8859-1"))) {
					item.setItemName(new String(item.getItemName().getBytes("iso8859-1"), "utf-8"));
				}
			} catch (UnsupportedEncodingException e) {
			}
		}
		vo.setObj(item);
		String currentTimePre = request.getParameter("currentTimePre");
		if (Validator.isNotNull(currentTimePre))
			vo.setParams("currentTimePre", currentTimePre);
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (Validator.isNotNull(rows)) {//rows为空表示不进行分页处理
			vo.setParams("pageSize", Validator.getDefaultStr(rows, "10"));
			vo.setParams("pageIndex", Validator.getDefaultStr(page, "1"));
			Page pageList = getBaseManager().getPageInfo(vo);//分页
			mapData.put("total", pageList.getCount());//dataGrid所需参数
			mapData.put("rows", pageList.getPageObjects());//dataGrid所需数据对象集合
		} else {
			List<BidItem> list = getBaseManager().getList(vo);
			if (!Validator.isEmpty(list)) {
				mapData.put("total", list.size());//dataGrid所需参数
				mapData.put("rows", list);//dataGrid所需数据对象集合
			}
		}
		return mapData;
	}

	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public ModelAndView view(HttpServletRequest request, String itemId) {
		ModelAndView view = null;
		if (StrUtil.isNull(itemId)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，itemId为空!");
			return view;
		}
		ParamsVo<BidItem> vo = new ParamsVo<BidItem>();
		vo.setInfoId(itemId);
		BidItem bidItem = (BidItem) bidItemManager.getInfoById(vo);
		if (bidItem == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到BidItem信息，itemId=" + itemId);
			return view;
		}

		ParamsVo<BidPub> bpubVo = new ParamsVo<BidPub>();
		BidPub pub = new BidPub();
		pub.setItemId(itemId);
		bpubVo.setObj(pub);
		bpubVo.setMethodKey("singlePubByAttr");
		BidPub bpub = (BidPub) bidPubManager.execute(bpubVo);
		if (bpub == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到pub信息，itemId=" + itemId);
			return view;
		}
		//		view = new ModelAndView("admin/viewJsp/" + viewMap.get(bidSession.getSessionType()));
		view = new ModelAndView("admin/viewJsp/item");
		view.addObject("bidItem", bidItem);
		view.addObject("bidPub", bpub);
		view.addObject("toType", request.getParameter("toType"));
		return view;
	}

	/**
	 * 保存item
	 */
	@RequestMapping(value = { "/rf" }, method = { RequestMethod.POST })
	@ResponseBody
	public ResultMsg saveInfo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute BidItem item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");

		ParamsVo<BidItem> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		//		vo.setParams("loginUser", PBOSSOTools.getLoginUser(request));//存放当前登录用户
		if (Validator.isNotNull(request.getParameter("bjServerStr")) && "0".equals(item.getSessionId())) {
			//单标保存时，单独设置报价服务器；
			LoginUser loginUser = (LoginUser) PBOSSOTools.getLoginUser(request);
			String[] bjServerStr = request.getParameter("bjServerStr").split(":");
			vo.setParams("bjServer", bjServerStr[0].trim());
			vo.setParams("bjPort", bjServerStr[1].trim());
			vo.setParams("createUserId", loginUser.getUserId());
			vo.setParams("createUserName", loginUser.getUserEname());
			vo.setParams("createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
		}
		if (Validator.isNotNull(item.getOrderNumber()) && !"0".equals(item.getOrderNumber())) {
			vo.setInfoId(item.getSessionId());
			vo.setKey("itemNum");
			Map map = (Map) bidItemManager.execute(vo);
			if (!Validator.isEmpty(map)) {
				long count = Long.parseLong(Validator.getDefaultStr(String.valueOf(map.get("ORDERNUMBER")),
						String.valueOf(map.get("COUNTNUM"))));
				long count2 = Long.parseLong(item.getOrderNumber());
				if (count2 <= count) {
					item.setOrderNumber(String.valueOf(count + 1));
				}
			}
			vo.setInfoId("");
			vo.setKey("");
		}
		vo.setObj(item);//新增
		vo.setKey("saveItem");
		ResultEntity entity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		String id = String.valueOf(entity.getEntity());
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "新增条目失败，请重试!");
		}
		return rmsg;
	}

	@RequestMapping(value = { "/rf/{id}" }, method = { RequestMethod.PUT })
	@ResponseBody
	public ResultMsg editInfo(HttpServletRequest request, HttpServletResponse response, @ModelAttribute BidItem item,
			@PathVariable String id) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "标的ID不能为空！");
			return rmsg;
		}

		ParamsVo<BidItem> vo = this.getParamsVo(request);//初始化参数vo对象，如果是登陆用户则获取用户信息及日志
		vo.setObj(item);//修改
		vo.setKey("editItem");
		ResultEntity entity = (ResultEntity) wbdProxyManager.saveInvoke(vo);//.editInfo(vo);
		String itemId = String.valueOf(entity.getEntity());
		if (Validator.isNull(itemId)) {
			rmsg = new ResultMsg("F", "操作失败！");
		}
		return rmsg;
	}

	@RequestMapping(value = "/itemBase", method = RequestMethod.GET)
	public ModelAndView editItemBase(HttpServletRequest request, String itemId) {
		ModelAndView view = null;
		if (StrUtil.isNull(itemId)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，itemId为空!");
			this.logger.error("缺少必要的参数，itemId为空!");
			return view;
		}

		ParamsVo<BidItem> vo = new ParamsVo<BidItem>();
		vo.setInfoId(itemId);
		BidItem bidItem = (BidItem) bidItemManager.getInfoById(vo);
		if (bidItem == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到bidItem信息，itemId=" + itemId);
		} else {
			view = new ModelAndView("/admin/viewJsp/itemBase");
			view.addObject("bidItem", bidItem);
			ParamsVo<BidSession> voSess = new ParamsVo<BidSession>();
			voSess.setInfoId(bidItem.getSessionId());
			String ifGroup = request.getParameter("ifGroup");
			if (Validator.isNotNull(ifGroup))
				view.addObject("ifGroup", ifGroup);
		}

		return view;
	}

	@RequestMapping(value = "/itemRule", method = RequestMethod.GET)
	public ModelAndView editItemRule(HttpServletRequest request, String itemId) {
		ModelAndView view = null;
		if (StrUtil.isNull(itemId)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，itemId为空!");
			this.logger.error("缺少必要的参数，itemId为空!");
			return view;
		}

		ParamsVo<BidItem> vo = new ParamsVo<BidItem>();
		vo.setInfoId(itemId);
		BidItem bidItem = (BidItem) bidItemManager.getInfoById(vo);
		if (bidItem == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到bidItem信息，itemId=" + itemId);
		} else {
			view = new ModelAndView("/admin/viewJsp/itemRule");
			view.addObject("bidItem", bidItem);
			String sessionMode = request.getParameter("sessionMode");
			String sessionType = request.getParameter("sessionType");
			if (Validator.isNotNull(sessionMode)) {
				view.addObject("sessionMode", sessionMode);
			}
			if (Validator.isNotNull(sessionType)) {
				view.addObject("sessionType", sessionType);
			} else {
				view.addObject("sessionType", "0");
			}
		}

		return view;
	}

	/**
	 * 发布标的：将标的的状态改为2，并把标的加载缓存	
	 * @return
	 */
	@RequestMapping(value = { "/start/{itemId}" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg startItem(HttpServletRequest request, HttpServletResponse response, @PathVariable String itemId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidItem> vo = this.getParamsVo(request);
		vo.setInfoId(itemId);
		vo.setKey("startItem");
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (resultEntity == null || !"true".equals(resultEntity.getResult())
				|| "false".equals(String.valueOf(resultEntity.getEntity()))) {
			rmsg = new ResultMsg("F", resultEntity.getMessage());
		}
		return rmsg;
	}

	/**
	 * 暂停标的：将标的的状态改为3，不移除标的缓存	
	 * @return
	 */
	@RequestMapping(value = { "/stop/{itemId}" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg stopItem(HttpServletRequest request, HttpServletResponse response, @PathVariable String itemId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidItem> vo = this.getParamsVo(request);
		vo.setInfoId(itemId);
		vo.setKey("stopItem");
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (resultEntity == null || !"true".equals(resultEntity.getResult())
				|| "false".equals(String.valueOf(resultEntity.getEntity()))) {
			rmsg = new ResultMsg("F", "操作失败");
		}
		return rmsg;
	}

	/**
	 * 继续启用标的：将标的的状态改回至2，
	 * @return
	 */
	@RequestMapping(value = { "/continue/{itemId}" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg continueItem(HttpServletRequest request, HttpServletResponse response, @PathVariable String itemId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidItem> vo = this.getParamsVo(request);
		vo.setInfoId(itemId);
		vo.setKey("continueItem");
		if (Validator.isNotNull(request.getParameter("firstBidTime"))) {
			vo.setParams("firstBidTime", request.getParameter("firstBidTime"));
		}
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if (resultEntity == null || !"true".equals(resultEntity.getResult())
				|| "false".equals(String.valueOf(resultEntity.getEntity()))) {
			rmsg = new ResultMsg("F", "操作失败");
		}
		return rmsg;
	}

	/**
	 * 恢复标的
	 * @return
	 */
	@RequestMapping(value = { "/restore" }, method = { RequestMethod.POST })
	@ResponseBody
	public ResultMsg restoreItem(HttpServletRequest request, HttpServletResponse response, String itemId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		response.setContentType("text/html");
		ParamsVo<BidItem> vo = this.getParamsVo(request);
		vo.setInfoId(itemId);
		String record = Validator.getDefaultStr(request.getParameter("record"), "T");
		vo.setParams("record", record);
		if (Validator.isNotNull(request.getParameter("firstBidTime"))) {
			vo.setParams("firstBidTime", request.getParameter("firstBidTime"));
		} else {
			vo.setParams("firstBidTime", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
		}
		if (Validator.isNotNull(request.getParameter("openTime"))) {
			vo.setParams("openTime", request.getParameter("openTime"));
		}
		vo.setKey("restoreItem");
		ResultEntity resultEntity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if ("false".equals(resultEntity.getResult())
				|| "false".equals(StrUtil.doNull(String.valueOf(resultEntity.getEntity()), "false"))) {
			rmsg = new ResultMsg("F", resultEntity.getMessage());
		}
		return rmsg;
	}

	@RequestMapping(value = { "/cacheList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object stopItemsss(HttpServletRequest request, HttpServletResponse response, String ids) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息
		String[] str = ids.split(",");
		List<String> keys = new ArrayList<String>();
		for (int i = 0; i < str.length; i++) {
			keys.add(str[i]);
		}
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		List list = cache.getObjects(keys, cache.item_prefix);

		return list;
	}

	@RequestMapping(value = { "/baojiaList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object stopItemBaojia(HttpServletRequest request, HttpServletResponse response, String itemId) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");//用于封装结果信息

		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		List list = (List) cache.getCacheCloneByKey(cache.jingjia_prefix + itemId);

		return list;
	}

	@RequestMapping(value = "/compareItem", method = RequestMethod.GET)
	public ModelAndView compareItem(HttpServletRequest request, String itemId) {
		ModelAndView view = new ModelAndView("/admin/viewJsp/compareItem");
		if (StrUtil.isNull(itemId)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，itemId为空!");
			this.logger.error("缺少必要的参数，itemId为空!");
			return view;
		}
		//查询标的缓存对象
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		boolean mark = cache.checkCacheObject(cache.item_prefix + itemId);
		if (mark) {
			BidItemCacheVo cacheVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + itemId);
			BidItem itemCache = (BidItem) cacheVo;
			view.addObject("itemCache", itemCache);
		}
		//查询标的数据库对象
		ParamsVo<BidItem> vo = new ParamsVo<BidItem>();
		vo.setInfoId(itemId);
		BidItem bidItem = (BidItem) bidItemManager.getInfoById(vo);
		if (bidItem == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到bidItem信息，itemId=" + itemId);
			return view;
		} else {
			view.addObject("bidItem", bidItem);
		}

		//查询标的price缓存对象
		BidCacheManager cachePrice = BidCacheFactory.getInstance().getCacheManager("itemPrice");
		boolean markPrice = cachePrice.checkCacheObject(cachePrice.item_price_prefix + itemId);
		if (markPrice) {
			BidItemPrice cachePriceVo = (BidItemPrice) cachePrice.getCacheCloneByKey(cachePrice.item_price_prefix
					+ itemId);
			BidItemPrice itemCachePrice = (BidItemPrice) cachePriceVo;
			view.addObject("itemPriceCache", itemCachePrice);
		}
		//查询标的price数据库对象
		ParamsVo<BidItemPrice> voPrice = new ParamsVo<BidItemPrice>();
		voPrice.setInfoId(itemId);
		BidItemPrice bidItemPrice = (BidItemPrice) bidItemPriceManager.getInfoById(voPrice);
		if (bidItemPrice == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到bidItemPrice信息，itemId=" + itemId);
		} else {
			view.addObject("bidItemPrice", bidItemPrice);
		}

		//查询数据库标的pub信息
		ParamsVo<BidPub> bpubVo = new ParamsVo<BidPub>();
		BidPub pub = new BidPub();
		if (!"0".equals(bidItem.getSessionId())) {
			pub.setSessionId(bidItem.getSessionId());
		} else {
			pub.setItemId(itemId);
		}
		bpubVo.setObj(pub);
		bpubVo.setMethodKey("singlePubByAttr");
		BidPub bpub = (BidPub) bidPubManager.execute(bpubVo);
		if (bpub == null) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "查不到pub信息，请确认是按照sessionId查还是按照itemId查。sessionId=" + bidItem.getSessionId()
					+ ",itemId=" + itemId);
			return view;
		} else {
			view.addObject("bidPub", bpub);
		}

		//查询缓存标的pub信息
		cache = BidCacheFactory.getInstance().getCacheManager("pub");
		String pubKey = cache.pub_prefix;
		if ("0".equals(bidItem.getSessionId())) {
			pubKey = pubKey + bidItem.getItemId();
		} else {
			pubKey = pubKey + bidItem.getSessionId();
		}
		mark = cache.checkCacheObject(pubKey);
		if (mark) {
			BidPub pubCache = (BidPub) cache.getCacheCloneByKey(pubKey);
			view.addObject("pubCache", pubCache);
		}

		return view;
	}

	public ResultMsg deleteInfo(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
		//初始化结果提示信息
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		response.setContentType("text/html");
		if (Validator.isNull(id)) {
			rmsg = new ResultMsg("F", "缺少必要的参数!");
			return rmsg;
		}
		ParamsVo<BidItem> vo = new ParamsVo<BidItem>();
		vo.setInfoId(id);
		vo.setParams("isDelete", "true");
		vo.setKey("delItem");
		ResultEntity entity = (ResultEntity) wbdProxyManager.saveInvoke(vo);
		if ("false".equals(entity.getResult())) {
			rmsg = new ResultMsg("F", "操作失败！");
		}
		return rmsg;
	}

	@Override
	protected UnityBaseManager<BidItem> getBaseManager() {
		return bidItemManager;
	}

	@Override
	protected String getCommBoxValue(BidItem item, String type) {
		if ("id".equals(type)) {
			return item.getItemId();
		} else {
			return item.getItemName();
		}
	}

	public void setBidItemManager(BidItemManager bidItemManager) {
		this.bidItemManager = bidItemManager;
	}

}
